package humanMirror.controller.actions;

import humanMirror.model.controller.Controller;
import humanMirror.model.human.Human;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class QuizAction implements Action {

    Controller controller;
    int questionNumber;

    String[] answers;

    public String perform(HttpServletRequest request,
                          HttpServletResponse response) {

        controller = (Controller) request.getSession().getAttribute("controller");
        questionNumber = (Integer) request.getSession().getAttribute("questionNumber");

        if (questionNumber==0) {
            prepareQuizList(request);
            //request.getSession().setAttribute("quizStarted", true);
            return "/quiz.jsp";
        } else {

            try {
                answers = request.getParameterValues("answers");

            } catch (Exception e) {
                e.printStackTrace();
            }

            controller.setAnswers(stringToInt(answers));

            if (questionNumber == controller.getCountOfQuestions()) {
                controller.stopAsking();
                request.getSession().setAttribute("questionNumber", 0);
                request.setAttribute("recomendations", controller.getRecommendationArray());
                request.getSession().setAttribute("controller", new Controller(new Human()));   // later need to save human state
                return "/answers.jsp";
            } else {
                prepareQuizList(request);
                return "/quiz.jsp";
            }
        }
    }//perform

    private void prepareQuizList(HttpServletRequest request) {
        request.setAttribute("question", controller.getQuestion(questionNumber));
        request.getSession().setAttribute("questionNumber", ++questionNumber);
        request.setAttribute("answersArray", controller.getAnswers());
    }

    protected int[] stringToInt(String[] inputArray) {
        if (inputArray == null) return new int[]{};
        int[] outPutArray = new int[inputArray.length];
        for (int i = 0; i < inputArray.length; i++) {
            outPutArray[i] = Integer.parseInt(inputArray[i]);
        }
        return outPutArray;
    }//stringToInt

}
